#include"shm.hpp"
#include"Log.hpp"

string transToHex(key_t k)
{
    char buffer[32];
    snprintf(buffer,sizeof(buffer),"0x%x",k);
    return buffer;
}
int main()
{
    //1.创建公共的key值
    key_t k=ftok(Path_NAME,PROJ_ID);
    assert(k!=-1);
    Log("create key done",DEBUG)<<"sever key"<<transToHex(k)<<endl;
    //2.创建共享内存，
    int shmid=shmget(k,SHM_SIZE,IPC_CREAT|IPC_EXCL| 0666);
    if(shmid==-1)
    {
        perror("shmget");
        exit(1);
    }
    //3.将指定的共享资源挂接地址空间
    char* shmaddr=(char*)shmat(shmid,nullptr,0);
    sleep(10);

    //通信逻辑
    //将共享内存看成大字符串，shmaddr是字符串首地址
    while(1)
    {
        printf("%s\n",shmaddr);
        if(strcmp(shmaddr,"quit")==0) break;
        sleep(1);
    }
    
    //4.将指定共享内存从地址空间失去关联
    int n=shmdt(shmaddr);
    assert(n!=-1);
    (void)n;
    //5.删除共享内存
    n=shmctl(shmid,IPC_RMID,nullptr);
    assert(n!=-1);
    (void)n;

    return 0;
}